//
//  CRWriteViewController.m
//  CRChatRoom
//
//  Created by lanou3g on 15/11/23.
//  Copyright © 2015年 SecondGroup. All rights reserved.
// 写说说的控制器

#import "CRWriteViewController.h"
#import "CRSetItem.h"
#import "CRSetGroup.h"
#import "CRSetArrowItem.h"
#import "CRWriteHeadView.h"
#import "CRTextView.h"
#import "MBProgressHUD+MJ.h"
#import "CRPhotosView.h"
#import "CRAddressController.h"
#import "MBProgressHUD+MJ.h"
@import CoreLocation;
@import MapKit;


@interface CRWriteViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, CLLocationManagerDelegate>
// 输入框
@property (nonatomic, weak) CRTextView *inputText;

/**
 *  添加图片的按钮
 */
@property (nonatomic, weak) UIButton *addButton;

/**
 *   存放选的的图片的view
 */
@property (nonatomic, weak) CRPhotosView *photosView;

/**
 *  存放图片的数组
 */
@property (nonatomic, strong) NSMutableArray *pics;

@property (nonatomic, strong) CLLocationManager *locationManager;

/**
 *  显示地理位置信息的文本框
 */
@property (nonatomic, strong) UITextField *addressInfo;

@end

@implementation CRWriteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置导航条内容
    [self setupNvbar];
    
    [self setupGroup0];
    
    // 设置地理位置
    [self setupAddress];
    
    // 设置显示地理位置信息的文本框
    [self setupAddressInfo];
    
    // 设置tableView距离上面为3
    self.tableView.contentInset = UIEdgeInsetsMake(5, 0, 0, 0);
    
}

// 设置显示地理位置信息的文本框
- (void)setupAddressInfo
{
    self.addressInfo = [[UITextField alloc] initWithFrame:CGRectMake(2, 350, 371, 40)];
    self.addressInfo.borderStyle = UITextBorderStyleRoundedRect;
    self.addressInfo.placeholder = @"请输入地址或进行定位";
    [self.tableView addSubview:self.addressInfo];
    
    
}

// 设置地理位置
- (void)setupAddress
{
    // 实例化LocationManager对象
    self.locationManager = [[CLLocationManager alloc] init];
    // 指定代理对象
    self.locationManager.delegate = self;
    
    
}

// 懒加载
- (NSMutableArray *)pics
{
    if (!_pics) {
        _pics = [NSMutableArray array];
    }
    return _pics;
}

// 设置导航条内容
- (void)setupNvbar
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(clickCancel)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发表" style:UIBarButtonItemStyleDone target:self action:@selector(clickpush)];
    self.title = @"写说说";
    
}

// 点击左上角取消按钮
- (void)clickCancel
{
    [self.navigationController popViewControllerAnimated:NO];
}

// 点击右上角发送按钮
- (void)clickpush
{
    
    // 发送文字和图片到服务器
    AVObject *post = [AVObject objectWithClassName:@"Post"];
    // 发送人的odjectId--便于查询
    [post setObject:[AVUser currentUser].objectId forKey:@"userID"];
    // 发送人的username--便于查询
    [post setObject:[AVUser currentUser].username forKey:@"username"];
    // 发送人的头像url--便于查询
    AVFile *file = [[AVUser currentUser] objectForKey:@"icon"];
    [post setObject:file.url forKey:@"iconUrl"];
    [post setObject:self.inputText.text forKey:@"content"];
    [post setObject:self.addressInfo.text forKey:@"address"];
    
    if (self.pics.count) {
        NSData *imageData = UIImagePNGRepresentation(self.pics.firstObject);
        AVFile *imageFile = [AVFile fileWithName:@"image.png" data:imageData];
        [post setObject:imageFile forKey:@"pics"];
        [self.pics removeAllObjects];
        
        
    
        
    }
    [post saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        while (self.photosView.subviews.firstObject) {
            [self.photosView.subviews.firstObject removeFromSuperview];
        }
        
        
        NSLog(@"%@", error);
        // 延迟2秒后发送状态
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 提示框
            [MBProgressHUD showSuccess:@"发表成功"];
        });
    }];
    
    [self.navigationController popViewControllerAnimated:NO];
    
    
}

// 第0组数据
- (void)setupGroup0
{
    CRSetItem *item00 = [CRSetItem itemWithIcon:@"iconfont-fujin" title:@"定位"];
    item00.option = ^{
        
//        // 开始更新位置信息
//        [self.locationManager startUpdatingLocation];
//        // 向用户发起定位请求
//        [self.locationManager requestAlwaysAuthorization];
//        // 显示提示信息
//        [MBProgressHUD showSuccess:@"定位时间较长.请多点几次"];
        
        // 直接写死位置
        self.addressInfo.text = @"北京市海淀区清河毛纺路金五星大厦";

    };
    CRSetItem *item01 = [CRSetArrowItem itemWithIcon:nil title:@"谁能看见" desvcClass:nil];
    CRSetGroup *group0 = [[CRSetGroup alloc] init];
    group0.items = @[item00, item01];
    [self.data addObject:group0];
}

// 返回头部View
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CRWriteHeadView *headView = [[CRWriteHeadView alloc] init];
    // 得到headView中的输入框和添加图片按钮
    self.inputText = headView.inputText;
    self.addButton = headView.addImageBt;
    self.photosView = headView.photosView;
    // 给添加图片按钮添加监听事件
    [self.addButton addTarget:self action:@selector(clickAdd) forControlEvents:UIControlEventTouchUpInside];
    return headView;
}

// 头部输入框的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 260;
}

// 点击添加图片按钮的方法
- (void)clickAdd
{
    // 模态图片选择控制器
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.delegate = self;
    [self presentViewController:ipc animated:NO completion:nil];
    
    
}

#pragma mark - 图片选择控制器的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    // 1. 销毁picker控制器
    [picker dismissViewControllerAnimated:NO completion:nil];
    // 2. 取得图片
    
    //初始化imageNew为从相机中获得的--
    
    UIImage *imageNew = info[UIImagePickerControllerOriginalImage];
    
//    //设置image的尺寸
//    
//    CGSize imagesize = imageNew.size;
//    
//    imagesize.height = imagesize.height * 0.3;
//    
//    imagesize.width = imagesize.width * 0.3;
//    
//    //对图片大小进行压缩--
//    
//    imageNew = [self imageWithImage:imageNew scaledToSize:imagesize];
//    
//    NSData *imageData = UIImageJPEGRepresentation(imageNew,0.5);
//    
//    UIImage *img = [UIImage imageWithData:imageData];
    
    // 把图片添加到本地数组- 最多只能选择5张
    if (self.pics.count == 5) {
        
        // 提示用户 只能选5张
        [MBProgressHUD showSuccess:@"一次只能发5张"];
        
        return;
    }
    [self.pics addObject:imageNew];
    // 添加原始高清图片
    [self.photosView addImage:imageNew];
    
    
    
}

// 界面一滑动 回收键盘
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

#pragma mark ---- Location Manager Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    // 停止更新位置信息
    [self.locationManager stopUpdatingLocation];
    
    // 地理编码
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:locations.lastObject completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        // 地标
        CLPlacemark *placemark = [placemarks lastObject];
        // 地址信息字典
        NSDictionary *addressDict = [placemark addressDictionary];
        
        NSLog(@"----%@", [addressDict[@"FormattedAddressLines"] lastObject]);
        self.addressInfo.text = [addressDict[@"FormattedAddressLines"] lastObject];
        
        
    }];
}



//对图片尺寸进行压缩--

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize

{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}


@end







